package com.efounder.chat.fragment;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.adapter.GroupUserSortAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.Group;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.GroupNameUtil;
import com.efounder.chat.utils.GroupUsersDialogHelper;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.mobilecomps.contacts.ChineseCharacterUtils;
import com.efounder.mobilecomps.contacts.ClearEditText;
import com.efounder.mobilecomps.contacts.HanyuParser;
import com.efounder.mobilecomps.contacts.PinyinComparator;
import com.efounder.mobilecomps.contacts.SideBar;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.thirdpartycomps.stickylistheaders.StickyListHeadersListView;
import com.efounder.utils.ResStringUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 群成员列表(属于ChatGroupUserActivity)
 *
 * @author yqs
 */
public class GroupUserFragment extends BaseFragment implements
        AdapterView.OnItemClickListener,
        AdapterView.OnItemLongClickListener,
        StickyListHeadersListView.OnHeaderClickListener,
        StickyListHeadersListView.OnStickyHeaderOffsetChangedListener,
        StickyListHeadersListView.OnStickyHeaderChangedListener {
    private StickyListHeadersListView stickyList;
    private SideBar sideBar;
    private TextView dialog;
    private GroupUserSortAdapter adapter;
    private boolean fadeHeader = true;
    private int groupId;//群号
    private int queryFrom;//从单纯从Groups查询是0，其他是1；
    private int createId;//群组创建者id
    private Group group;
    private TextView tv_m_total;//显示群成员人数
    private GroupUsersDialogHelper helper;
    private boolean isCreateor = false;//当前登录用户是否是创建者
    private int appUserId;//当前登录的用户
    private User appLoginUser;

    /**
     * 汉字转换成拼音的类
     */
    private List<User> sourceDataList;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private AsyncTask<Void, Void, String> asyncTask;

    private ClearEditText mClearEditText;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_groupuserlist, container,
                false);
        groupId = getActivity().getIntent().getIntExtra("id", 1);
        queryFrom = getActivity().getIntent().getIntExtra("queryFrom", 1);
        helper = new GroupUsersDialogHelper(getActivity(), groupId, new UpdateDataCallBack() {
            @Override
            public void updateDataNotication() {
                tv_m_total.setText("(" + String.valueOf(sourceDataList.size()) + ")");
                List<User> tempList = filledData(sourceDataList);
                sourceDataList.clear();
                sourceDataList.addAll(tempList);
                // 根据a-z进行排序源数据
                Collections.sort(sourceDataList, pinyinComparator);
                adapter = new GroupUserSortAdapter(getActivity(), sourceDataList, group);
                stickyList.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        });
        appUserId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID));

        initViews(view);

        loadData();
        return view;
    }

    private void initViews(View view) {

        mClearEditText = (ClearEditText) view.findViewById(R.id.filter_edit);

        // 根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(textWatcher);
        //EditText获取焦点后隐藏掉提示文字
        mClearEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                ClearEditText editText = (ClearEditText) v;
                String hint = null;

                int i = v.getId();
                if (i == R.id.filter_edit) {
                    if (hasFocus) {
                        hint = editText.getHint().toString();
                        editText.setTag(hint);
                        editText.setHint("");
                    } else {
                        hint = editText.getTag().toString();
                        editText.setHint(hint);
                    }

                }
            }
        });


        // 实例化汉字转拼音类

        pinyinComparator = new PinyinComparator();
        tv_m_total = (TextView) view.findViewById(R.id.tv_m_total);
        sideBar = (SideBar) view.findViewById(R.id.sidrbar);
        dialog = (TextView) view.findViewById(R.id.dialog);
        sideBar.setTextView(dialog);
        appLoginUser = new User();

        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    stickyList.setSelection(position);
                }

            }
        });

        stickyList = (StickyListHeadersListView) view
                .findViewById(R.id.country_lvcountry);
        stickyList.setOnItemClickListener(this);
        stickyList.setOnItemLongClickListener(this);
        stickyList.setOnHeaderClickListener(this);
        stickyList.setOnStickyHeaderChangedListener(this);
        stickyList.setOnStickyHeaderOffsetChangedListener(this);
        stickyList.setDrawingListUnderStickyHeader(true);
        stickyList.setAreHeadersSticky(true);
        stickyList.setStickyHeaderTopOffset(-10);
        stickyList.setFastScrollEnabled(true);
        stickyList.setFastScrollAlwaysVisible(true);
        sourceDataList = new ArrayList<User>();


    }

    @Override
    public void onResume() {
        super.onResume();

    }

    //加载数据
    private void loadData() {
        sourceDataList.clear();

        if (queryFrom == 1) {
            group = WeChatDBManager.getInstance().getGroupWithUsers(groupId);
        } else {
            group = WeChatDBManager.getInstance().getGroupWithUsersInGroups(groupId);
        }
        createId = group.getCreateId();
        if (createId == appUserId) {
            isCreateor = true;
        }

        List<User> myList = group.getUsers();
        tv_m_total.setText("(" + String.valueOf(myList.size()) + ")");

        // 根据a-z进行排序源数据
        sortByAsync(myList);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {

        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mClearEditText.removeTextChangedListener(textWatcher);
    }

    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
            filterData(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().equals("")) {
            }
        }
    };

    /**
     * 为ListView填充数据
     *
     * @param users
     * @return
     */
    private List<User> filledData(List<User> users) {
        List<User> usersList = new ArrayList<User>();

        // String[] idData = getResources().getStringArray(R.array.id);
        for (User user : users) {
            // 汉字转换成拼音
            String userName = "";
            // User friendUser = GroupNameUtil.getGroupUser(group.getGroupId(), user.getId(), WeChatDBManager.getInstance());
            if (!user.getNickName().equals(String.valueOf(user.getId()))) {
                userName = GroupNameUtil.getGroupUserName(user);
            } else {
                userName = user.getNickName();
            }
            user.setOtherGroupRemark(userName);
            if (user.getId() == appUserId) {
                appLoginUser = user;
            }
            try {
                String sortString = "";
                String pinyin = null;
                //获取名字的简拼
                pinyin = ChineseCharacterUtils.getJianPin(userName);
                sortString = pinyin.substring(0, 1).toUpperCase(
                        Locale.getDefault());

                if (user.getGroupUserType() == User.GROUPCREATOR || group.getCreateId() == user.getId()) {
                    user.setSortLetters("↑");
                } else if (user.getGroupUserType() == User.GROUPMANAGER) {
                    user.setSortLetters("☆");
                } else if (sortString.matches("[A-Z]")) {// 正则表达式，判断首字母是否是英文字母
                    //按照username的简拼进行排序
                    user.setSortLetters(pinyin.toUpperCase(Locale.getDefault()));
                } else {
                    user.setSortLetters("#");
                }
            } catch (Exception e) {
                e.printStackTrace();
                user.setSortLetters("#");
            }
            usersList.add(user);

        }

        return usersList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<User> filterDateList = new ArrayList<User>();

        if (TextUtils.isEmpty(filterStr)) {
            if (sourceDataList != null) {
                filterDateList = sourceDataList;
            }
        } else {
            filterDateList.clear();
            for (User user : sourceDataList) {
                String name = user.getOtherGroupRemark();
                if (containString(name, filterStr)) {
                    filterDateList.add(user);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        if (filterDateList != null && adapter != null) {
            adapter.updateListView(filterDateList);
        }

    }

    private boolean containString(String name, String filterStr) {
        String namePinyin = new HanyuParser().getStringPinYin(name);
        for (int i = 0; i < filterStr.length(); i++) {
            String singleStr = filterStr.substring(i, i + 1);
            // 汉字
            if (name.contains(singleStr)) {
                if (i == filterStr.length() - 1) {
                    return true;
                }
                continue;
            }
            // 英文
            if (namePinyin.contains(singleStr)) {
                int currentIndex = namePinyin.indexOf(singleStr);
                namePinyin = namePinyin.substring(currentIndex + 1,
                        namePinyin.length());
            } else {// 不包含
                break;
            }
            if (i == filterStr.length() - 1) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onStickyHeaderOffsetChanged(StickyListHeadersListView l,
                                            View header, int offset) {
        if (fadeHeader
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            header.setAlpha(1 - (offset / (float) header.getMeasuredHeight()));
        }
    }

    @Override
    public void onStickyHeaderChanged(StickyListHeadersListView l, View header,
                                      int itemPosition, long headerId) {
        header.setAlpha(1);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        User user = (User) adapter.getItem(position);
        Intent intent = new Intent();
        intent.putExtra("id", user.getId());
        intent.putExtra("groupId", groupId);
        intent.putExtra("position", position);
        ChatActivitySkipUtil.startUserInfoActivityForResult(getActivity(), intent, 1);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {
            if (data.hasExtra("delete")) {
                sourceDataList.remove(data.getIntExtra("position", 0));
                adapter.notifyDataSetChanged();
            } else if (data.hasExtra("remarkName")) {
                sourceDataList.get(data.getIntExtra("position", 0)).setOtherGroupRemark(data.getStringExtra("remarkName"));
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onHeaderClick(StickyListHeadersListView l, View header,
                              int itemPosition, long headerId, boolean currentlySticky) {

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        User user = (User) adapter.getItem(position);
        //只有是群主或者管理员才能进行该操作

        //如果当前登陆的用户是管理员或者群主 && 当前长按的用户不是群主也不是自己 && 当前长按的用户不是管理员    那么显示弹框(
//        if ((appLoginUser.getGroupUserType() == User.GROUPMANAGER || appLoginUser.getGroupUserType() == User.GROUPCREATOR)
//                && user.getId() != createId
//                && user.getId() != appUserId
//                && (user.getGroupUserType()!= User.GROUPMANAGER )) {
//            helper.showDialog(user, isCreateor, sourceDataList);
//        }


        if (appLoginUser.getGroupUserType() == User.GROUPMANAGER || appLoginUser.getGroupUserType() == User.GROUPCREATOR
                || appLoginUser.getId() == group.getCreateId()) {
            if ((appLoginUser.getGroupUserType() == User.GROUPCREATOR || appLoginUser.getId() == group.getCreateId())
                    && user.getId() != appUserId
            ) {
                helper.showDialog(user, isCreateor, sourceDataList);
            } else if (appLoginUser.getGroupUserType() != User.GROUPCREATOR
                    && user.getId() != appUserId
                    && user.getGroupUserType() != User.GROUPMANAGER
                    && user.getGroupUserType() != User.GROUPCREATOR) {
                helper.showDialog(user, isCreateor, sourceDataList);
            }
        }

        return true;
    }

    /**
     * 更新界面
     */
    public interface UpdateDataCallBack {
        public void updateDataNotication();
    }


    //排序
    private void sortByAsync(final List<User> myList) {

        //todo rxjava 实现异步
        Disposable disposable = Observable.create(new ObservableOnSubscribe<List<User>>() {

            @Override
            public void subscribe(ObservableEmitter<List<User>> emitter) throws Exception {
                sourceDataList.addAll(filledData(myList));
                Collections.sort(sourceDataList, pinyinComparator);
                emitter.onNext(sourceDataList);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(@NonNull Disposable disposable) throws Exception {
                showLoading(ResStringUtil.getString(R.string.common_text_loading));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<User>>() {
            @Override
            public void accept(List<User> users) throws Exception {

                dismissLoading();


                int posotion = stickyList.getFirstVisiblePosition();
                adapter = new GroupUserSortAdapter(getActivity(), sourceDataList, group);
                stickyList.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                stickyList.setSelection(posotion);
            }
        });

//        if (true) {
//            return;
//        }

//        asyncTask = new AsyncTask<Void, Void, String>() {
//
//            @Override
//            protected void onPreExecute() {
//                super.onPreExecute();
//                progressDialog.show();
//            }
//
//            @Override
//            protected String doInBackground(Void... params) {
//                sourceDataList.addAll(filledData(myList));
//                Collections.sort(sourceDataList, pinyinComparator);
//                return null;
//            }
//
//            @Override
//            protected void onPostExecute(String result) {
//                super.onPostExecute(result);
//                progressDialog.dismiss();
//                int posotion = stickyList.getFirstVisiblePosition();
//                adapter = new GroupUserSortAdapter(getActivity(), sourceDataList, group);
//                stickyList.setAdapter(adapter);
//                adapter.notifyDataSetChanged();
//                stickyList.setSelection(posotion);
//            }
//
//            @Override
//            protected void onCancelled() {
//                super.onCancelled();
//                progressDialog.dismiss();
//            }
//        };
//        asyncTask.executeOnExecutor(Executors.newCachedThreadPool());

    }
}

